using System.Text;
using System.Text.Json;
using KnowledgeQA.Web.Models;

namespace KnowledgeQA.Web.Services
{
    /// <summary>
    /// API服务类
    /// </summary>
    public class ApiService
    {
        private readonly ApiSettings _apiSettings;
        private readonly HttpClient _httpClient;
        private readonly ILogger<ApiService> _logger;

        public ApiService(ApiSettings apiSettings, ILogger<ApiService> logger)
        {
            _apiSettings = apiSettings;
            _logger = logger;
            _httpClient = new HttpClient
            {
                Timeout = TimeSpan.FromMilliseconds(_apiSettings.Timeout)
            };
        }

        /// <summary>
        /// 构建完整的API URL
        /// </summary>
        /// <param name="baseUrl">基础URL</param>
        /// <param name="endpoint">端点</param>
        /// <param name="parameters">参数</param>
        /// <returns>完整的URL</returns>
        private string BuildUrl(string baseUrl, string endpoint, Dictionary<string, string>? parameters = null)
        {
            var url = $"{baseUrl.TrimEnd('/')}{endpoint}";
            
            if (parameters != null && parameters.Any())
            {
                var queryString = string.Join("&", parameters.Select(p => $"{p.Key}={Uri.EscapeDataString(p.Value)}"));
                url += $"?{queryString}";
            }
            
            return url;
        }

        /// <summary>
        /// 替换URL中的占位符
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="placeholders">占位符值</param>
        /// <returns>替换后的URL</returns>
        private string ReplacePlaceholders(string url, Dictionary<string, string> placeholders)
        {
            foreach (var placeholder in placeholders)
            {
                url = url.Replace($"{{{placeholder.Key}}}", placeholder.Value);
            }
            return url;
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="url">请求URL</param>
        /// <returns>响应数据</returns>
        public async Task<T?> GetAsync<T>(string url)
        {
            try
            {
                _logger.LogInformation("发送GET请求: {Url}", url);
                
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                
                var content = await response.Content.ReadAsStringAsync();
                return JsonSerializer.Deserialize<T>(content, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "GET请求失败: {Url}", url);
                throw;
            }
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="url">请求URL</param>
        /// <param name="data">请求数据</param>
        /// <returns>响应数据</returns>
        public async Task<T?> PostAsync<T>(string url, object? data = null)
        {
            try
            {
                _logger.LogInformation("发送POST请求: {Url}", url);
                
                HttpContent? content = null;
                if (data != null)
                {
                    var json = JsonSerializer.Serialize(data);
                    content = new StringContent(json, Encoding.UTF8, "application/json");
                }
                
                var response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                
                var responseContent = await response.Content.ReadAsStringAsync();
                return JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "POST请求失败: {Url}", url);
                throw;
            }
        }

        /// <summary>
        /// 发送PUT请求
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="url">请求URL</param>
        /// <param name="data">请求数据</param>
        /// <returns>响应数据</returns>
        public async Task<T?> PutAsync<T>(string url, object? data = null)
        {
            try
            {
                _logger.LogInformation("发送PUT请求: {Url}", url);
                
                HttpContent? content = null;
                if (data != null)
                {
                    var json = JsonSerializer.Serialize(data);
                    content = new StringContent(json, Encoding.UTF8, "application/json");
                }
                
                var response = await _httpClient.PutAsync(url, content);
                response.EnsureSuccessStatusCode();
                
                var responseContent = await response.Content.ReadAsStringAsync();
                return JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "PUT请求失败: {Url}", url);
                throw;
            }
        }

        /// <summary>
        /// 发送DELETE请求
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="url">请求URL</param>
        /// <returns>响应数据</returns>
        public async Task<T?> DeleteAsync<T>(string url)
        {
            try
            {
                _logger.LogInformation("发送DELETE请求: {Url}", url);
                
                var response = await _httpClient.DeleteAsync(url);
                response.EnsureSuccessStatusCode();
                
                var content = await response.Content.ReadAsStringAsync();
                return JsonSerializer.Deserialize<T>(content, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "DELETE请求失败: {Url}", url);
                throw;
            }
        }

        /// <summary>
        /// 发送文件上传请求
        /// </summary>
        /// <typeparam name="T">响应类型</typeparam>
        /// <param name="url">请求URL</param>
        /// <param name="fileStream">文件流</param>
        /// <param name="fileName">文件名</param>
        /// <param name="parameters">其他参数</param>
        /// <returns>响应数据</returns>
        public async Task<T?> UploadFileAsync<T>(string url, Stream fileStream, string fileName, Dictionary<string, string>? parameters = null)
        {
            try
            {
                _logger.LogInformation("发送文件上传请求: {Url}, 文件名: {FileName}", url, fileName);
                
                using var formData = new MultipartFormDataContent();
                
                // 添加文件
                var fileContent = new StreamContent(fileStream);
                formData.Add(fileContent, "file", fileName);
                
                // 添加其他参数
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        formData.Add(new StringContent(param.Value), param.Key);
                    }
                }
                
                var response = await _httpClient.PostAsync(url, formData);
                response.EnsureSuccessStatusCode();
                
                var content = await response.Content.ReadAsStringAsync();
                return JsonSerializer.Deserialize<T>(content, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "文件上传失败: {Url}, 文件名: {FileName}", url, fileName);
                throw;
            }
        }

        /// <summary>
        /// 获取文档API URL
        /// </summary>
        /// <param name="endpoint">端点</param>
        /// <param name="placeholders">占位符</param>
        /// <param name="parameters">查询参数</param>
        /// <returns>完整的URL</returns>
        public string GetDocumentApiUrl(string endpoint, Dictionary<string, string>? placeholders = null, Dictionary<string, string>? parameters = null)
        {
            var url = BuildUrl(_apiSettings.DocumentApi.BaseUrl, endpoint, parameters);
            
            if (placeholders != null)
            {
                url = ReplacePlaceholders(url, placeholders);
            }
            
            return url;
        }

        /// <summary>
        /// 获取问答API URL
        /// </summary>
        /// <param name="endpoint">端点</param>
        /// <param name="placeholders">占位符</param>
        /// <param name="parameters">查询参数</param>
        /// <returns>完整的URL</returns>
        public string GetQaApiUrl(string endpoint, Dictionary<string, string>? placeholders = null, Dictionary<string, string>? parameters = null)
        {
            var url = BuildUrl(_apiSettings.QaApi.BaseUrl, endpoint, parameters);
            
            if (placeholders != null)
            {
                url = ReplacePlaceholders(url, placeholders);
            }
            
            return url;
        }
    }
} 